﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WarehouseManagement.DataAccess;

namespace WarehouseManagement.BusinessLogic.BC
{
    public class DataChangedLogBC : BaseBC
    {
        public bool IsImportDataChanged(int merchandiseId, int month, int year)
        {
            var item = GetDataChangedLogItem(merchandiseId, month, year);
            if (item == null)
                return false;
            return item.ImportDataChanged;
        }

        public bool IsExportDataChanged(int merchandiseId, int month, int year)
        {
            var item = GetDataChangedLogItem(merchandiseId, month, year);
            if (item == null)
                return false;
            return item.ExportDataChanged;
        }

        private DataChangedLog GetDataChangedLogItem(int merchandiseId, int month, int year)
        {
            var item = Context.DataChangedLogs.SingleOrDefault(e => e.MerchandiseId == merchandiseId
                && e.Month == month
                && e.Year == year);
            return item;
        }

        private void SetDataChange(int merchandiseId, int month, int year,
            bool? importDataChanged = null, bool? exportDataChanged = null)
        {
            var item = GetDataChangedLogItem(merchandiseId, month, year);
            if (item == null)
            {
                Context.DataChangedLogs.InsertOnSubmit(new DataChangedLog()
                {
                    Id = Guid.NewGuid(),
                    ExportDataChanged = exportDataChanged.HasValue ? exportDataChanged.Value : false,
                    ImportDataChanged = importDataChanged.HasValue ? importDataChanged.Value : false,
                    Year = year,
                    Month = month,
                    MerchandiseId = merchandiseId
                });
            }
            else
            {
                if (importDataChanged.HasValue)
                    item.ImportDataChanged = importDataChanged.Value;
                if (exportDataChanged.HasValue)
                    item.ExportDataChanged = exportDataChanged.Value;
            }
        }

        public void SetImportDataChanged(int merchandiseId, int month, int year, bool changed)
        {
            SetDataChange(merchandiseId, month, year, changed);
            SubmitChanges();
        }

        public void SetExportDataChanged(int merchandiseId, int month, int year, bool changed)
        {
            SetDataChange(merchandiseId, month, year, exportDataChanged: changed);
            SubmitChanges();
        }

       
    }
}
